@file:Suppress("DEPRECATION")

package com.juku2024.juku.tools

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Process
import android.os.StrictMode
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.SDCardUtils
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.HomeModel
import com.wanban.adutils.AdUtils
import com.juku2024.juku.VideoDetailActivity
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.text.DecimalFormat
import java.util.*

object AppUtils {
    const val PLATFORM = "mobile-android"
    private const val mateChannelKey = "CHANNEL_VALUE"
    private const val mateUmengKey = "UMENG_KEY"
    private const val IRON_SOURCE_APP_KEY = "IRON_SOURCE"
    private const val SHARE_URL = "SHARE_URL"

    /**
     * 获取 MetaValue
     * @param context 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    fun getMetaValue(context: Context?, key: String): String {
        if (context == null) {
            return "unknown"
        }
        var channelName = "unknown"
        try {
            val packageManager = context.packageManager
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                val applicationInfo =
                    packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
                if (applicationInfo.metaData != null) {
                    channelName = applicationInfo.metaData.getString(key)?:"unknown"
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return channelName
    }

    fun getIronSourceAppKey(activity: Activity): String {
        return getMetaValue(activity, IRON_SOURCE_APP_KEY)
    }

    fun getChannelValue(): String {
        return getMetaValue(BaseApplication.context, mateChannelKey)
    }


    fun getShareUrl(context: Context): String {
        return String.format("https://play.google.com/store/apps/details?id=%s", context.packageName)
    }

    fun getDeviceId(): String {
//        val context = BaseApplication.context
//        val umengId = UMConfigure.getUMIDString(context)
//        if (TextUtils.isEmpty(umengId)) {
//            return ""
//        }
//        return MD5Utils.getMD5String(umengId + context.packageName)
        return SPUtil.instance.userId
    }

    /**
     * 获得当前进程的名字
     * @param context
     * @return 进程号
     */
    fun getCurProcessName(context: Context?): String? {
        if (context == null) return null
        var currentProcessName: String? = null
        try {
            val activityManager = context.getSystemService(Application.ACTIVITY_SERVICE) as ActivityManager
            if (activityManager.runningAppProcesses.isNullOrEmpty()) return null
            val pid = Process.myPid()
            for (appProcess in activityManager.runningAppProcesses) {
                if (appProcess.pid == pid) {
                    currentProcessName = appProcess.processName
                    break
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return currentProcessName
    }

    fun getColor(colorID: Int): Int {
        return ContextCompat.getColor(BaseApplication.context, colorID)
    }

    @Suppress("DEPRECATION")
    fun getVersionCode(): Int {
        val manager = BaseApplication.context.packageManager//获取包管理器
        try {
            //通过当前的包名获取包的信息
            val info = manager.getPackageInfo(BaseApplication.context.packageName, 0)//获取包对象信息
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                info.longVersionCode.toInt()
            } else {
                info.versionCode
            }

        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return 0
    }

    /**
     * 返回版本名字
     * 对应build.gradle中的versionName
     *
     * @return String
     */
    fun getVersionName(): String {
        var versionName = ""
        try {
            val packageManager = BaseApplication.context.packageManager
            val packInfo = packageManager.getPackageInfo(BaseApplication.context.packageName, 0)
            versionName = packInfo.versionName?:""
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return versionName
    }

    fun getString(@StringRes strID: Int): String {
        return BaseApplication.context.resources.getString(strID)
    }

    /**
     * 打开软键盘
     *
     * @param mEditText
     */
    fun openKeyboard(mEditText: EditText?) {
        if (mEditText == null) return
        val imm = mEditText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED)
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText
     */
    fun closeKeyboard(mEditText: EditText?) {
        if (mEditText == null) return
        val imm = mEditText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(mEditText.windowToken, 0)
    }

    fun findAppCompatActivity(context: Context?): AppCompatActivity? {
        if (context == null) return null
        if (context is AppCompatActivity) {
            return context
        }
        return if (context is ContextWrapper) {
            findAppCompatActivity(context.baseContext)
        } else {
            null
        }
    }

    fun findActivity(context: Context?): Activity? {
        if (context == null) return null
        if (context is Activity) {
            return context
        }
        return if (context is ContextWrapper) {
            findActivity(context.baseContext)
        } else {
            null
        }
    }

    @Suppress("DEPRECATION")
    fun getRunningTaskCount(context: Context): Int {
        return try {
            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                (am.appTasks?.firstOrNull()?.taskInfo?.numActivities)?:1
            } else {
                (am.getRunningTasks(1)?.firstOrNull()?.numActivities)?:1
            }
        }catch (e: Exception) {
            e.printStackTrace()
            1
        }
    }

    /**
     * 将字节转为其他单位
     * @param bit
     * @return
     */
    fun getStoreSize(bit: Long): String {
        val decimalFormat = DecimalFormat("0.0")
        val finalSize: String = when {
            bit < 1000 -> { // 1B...999B
                bit.toString() + "B"
            }
            bit < 1022976 -> { // 0.1KB...999KB
                decimalFormat.format((bit / 1024f).toDouble()) + "KB"
            }
            bit < 1047527424 -> { // 0.1MB...999MB
                decimalFormat.format((bit / 1048576f).toDouble()) + "MB"
            }
            else -> { // 0.1GB
                decimalFormat.format((bit / 1073741824f).toDouble()) + "GB"
            }
        }
        return finalSize
    }

    fun getCacheMemory(): String {
        val path = BaseApplication.context.externalCacheDir?:return "0MB"
        val cacheMemorySize = FileUtils.getLength(path.absolutePath)
        return ConvertUtils.byte2FitMemorySize(cacheMemorySize, 0)
    }

    fun toWeb(url: String) {
        if (!TextUtils.isEmpty(url)) {
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val contentUrl = Uri.parse(url)
            intent.data = contentUrl
            BaseApplication.context.startActivity(intent)
        }
    }

    fun getCountryCode(): String {
        val locale: Locale? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            var targetLocal: Locale? = null
            val localList = BaseApplication.context.resources.configuration.locales
            val size = localList.size()
            for (index in 0 until size) {
                val local = localList.get(index)
                if (!TextUtils.isEmpty(local.country)) {
                    targetLocal = local
                    break
                }
            }
            targetLocal
        } else {
            BaseApplication.context.resources.configuration.locale
        }
        return locale?.country?:"unknown"
    }

    fun launchAppDetail(context: Context, appPkg: String) {    //appPkg 是应用的包名
        val goolePlay = "com.android.vending"//这里对应的是谷歌商店，跳转别的商店改成对应的即可
        try {
            val uri = Uri.parse("market://details?id=$appPkg")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            intent.setPackage(goolePlay)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        } catch (ignored: Exception) {

        }

    }


    fun clearCache() {
        RxUtils.doObservable<Boolean> {
            // 清空所有的版本表
            AdUtils.clearAdCache()
            NoteRoomUtils.getInstance().albumDao().deleteAll()
            NoteRoomUtils.getInstance().unlockMoreDao().delete()
            NoteRoomUtils.getInstance().homeGenreDao().delete()
            NoteRoomUtils.getInstance().hotDao().delete()
            NoteRoomUtils.getInstance().limitDao().deleteAll()
            NoteRoomUtils.getInstance().versionDao().deleteAll()
            NoteRoomUtils.getInstance().videoVersionDao().deleteAll()
            NoteRoomUtils.getInstance().videoDetailDao().deleteAll()
            NoteRoomUtils.getInstance().videoEntityDao().deleteAll()
            // 清空本地文件夹缓存内容
            val dir = BaseApplication.context.externalCacheDir
            dir?.deleteRecursively()

            val homeDao = NoteRoomUtils.getInstance().homeTabDao()
            val homeTab = homeDao.query()
            homeDao.delete()
            val homeTabModel = HomeModel(0, homeTab?.aoe, 0, null, homeTab?.analysis)
            homeDao.insert(homeTabModel)

            if (!it.isDisposed)
                it.onComplete()
        }

    }



    fun setAppStyle(activity: AppCompatActivity){
        changeNightStyle(activity)
    }

    fun changeNightStyle(activity: AppCompatActivity){
        activity.delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
        //设置夜间模式背景色
        activity.window.statusBarColor = Color.BLACK
        activity.window.navigationBarColor = Color.BLACK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val controller = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
            controller.isAppearanceLightStatusBars = false
        } else {
            activity.window.decorView.systemUiVisibility = 0
        }
    }

    fun changeDayStyle(activity: AppCompatActivity){
        LogC.e("changeNightStyle。。。。。切换日间模式。。。。" )
        activity.delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
        if (activity is VideoDetailActivity) {
            activity.window.statusBarColor = Color.BLACK
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val controller = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
                controller.isAppearanceLightStatusBars = false
            } else {
                activity.window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                activity.window.decorView.systemUiVisibility = 0
            }
        } else {
            activity.window.statusBarColor = Color.WHITE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val controller = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
                controller.isAppearanceLightStatusBars = true
            } else {
                activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }

    }



    fun method01(): String {
        return readStringFromAssets("method01.crt")
    }
    fun method02(): String {
        return readStringFromAssets("method02.crt")
    }
    fun method03(): String {
        return readStringFromAssets("method03.crt")
    }
    fun method04(): String {
        return readStringFromAssets("method04.crt")
    }
    fun method05(): String {
        return readStringFromAssets("method05.crt")
    }
    fun method06(): String {
        return readStringFromAssets("method06.crt")
    }
    fun method07(): String {
        return readStringFromAssets("method07.crt")
    }


    private fun readStringFromAssets(fileName: String): String {
        //通过设备管理对象 获取Asset的资源路径
        val assetManager: AssetManager = BaseApplication.context.assets
        var inputStream: InputStream? = null
        var isr: InputStreamReader? = null
        var br: BufferedReader? = null
        val sb = StringBuffer()
        try {
            inputStream = assetManager.open(fileName)
            isr = InputStreamReader(inputStream)
            br = BufferedReader(isr)
            sb.append(br.readLine())
            var line: String
            while (br.readLine().also { line = it } != null) {
                sb.append(line)
            }
            br.close()
            isr.close()
            inputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                br?.close()
                isr?.close()
                inputStream?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

    fun getSourceName(sourceId: Int): String {
        val sourceName: String = when (sourceId) {
            21 -> "超清T"
            22 -> "超清I"
            23 -> "超清Y"
            24 -> "超清M"
            25 -> "超清L"
            26 -> "超清S"
            27 -> "超清P"
            28 -> "超清B"
            else -> String.format(Locale.getDefault(), "线路%d", sourceId)
        }
        return sourceName
    }



    /** 分享当前App */
    fun shareApp(context: Context) {
        val shareUrl = getShareUrl(context)
        val intent = Intent()
        intent.action = Intent.ACTION_SEND
        intent.putExtra(Intent.EXTRA_TEXT, shareUrl)
        intent.type = "text/plain"
        context.startActivity(intent)
    }

    /**
     * 共有file
     *
     */
    fun shareFile(context: Context, file: File) {
        val builder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        var intent = Intent(Intent.ACTION_SEND)
        //二进制的方式传输
        intent.type = "application/octet-stream"
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file))
        intent = Intent.createChooser(intent, " ")
        context.startActivity(intent)
    }

    /**
     * 获得当前进程的名字
     * @param context
     * @return 进程号
     */
    fun getMainProcessName(context: Context): String? {
        val pid = Process.myPid()
        var mainProcessName: String? = null
        val activityManager = context.getSystemService(Application.ACTIVITY_SERVICE) as ActivityManager
        activityManager.runningAppProcesses?.forEach { appProcess ->
            if (appProcess.pid == pid) {
                mainProcessName = appProcess.processName
                return@forEach
            }
        }
        return mainProcessName
    }



    /**
     * 高版本判断是否有sdcard
     */
    fun hasTFPath(): Boolean {
        //如果有2个文件，一般第一个是内置，第二个外置
        val files: Array<File> = BaseApplication.context.externalCacheDirs
        return files.size > 1
    }

    /**
     * 判断是否存在外置tf卡
     */
    fun isStorageTf(): Boolean {
        return SDCardUtils.isSDCardEnableByEnvironment() && hasTFPath()
    }


    /**
     * 获取手机内部可用空间大小
     * @return 大小，字节为单位
     */
    fun getAvailableSdcardMemorySize(): Long {
        return SDCardUtils.getExternalAvailableSize()
    }

    /**
     * 获取手机内部可用空间大小
     * @return 大小，字节为单位
     */
    fun getAvailableInternalMemorySize(): Long {
        return SDCardUtils.getInternalAvailableSize()
    }

}